package cn.luyou.admin.service.impl;

import cn.luyou.admin.common.JwtUtils;
import cn.luyou.admin.common.PasswordUtils;
import cn.luyou.admin.entity.LoginResponse;
import cn.luyou.admin.entity.User;
import cn.luyou.admin.mapper.UserMapper;
import cn.luyou.admin.service.UserService;
import cn.luyou.admin.utils.BaseContext;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Autowired
    private JwtUtils jwtUtils;

    @Autowired
    private PasswordUtils passwordUtils;

    @Override
    public LoginResponse login(String username, String password) {
        User user = this.getOne(new LambdaQueryWrapper<User>()
                .eq(User::getUsername, username));
        if (user == null) {
            throw new IllegalArgumentException("用户不存在");
        }
        if (!passwordUtils.checkPassword(password, user.getPassword())) {
            throw new IllegalArgumentException("密码错误");
        }
        String s = jwtUtils.generateToken(user.getId(), username, user.getRole());
        LoginResponse response = new LoginResponse();
        response.setToken(s);
        response.setUserName(user.getUsername());
        response.setRole(user.getRole());
        return response;
    }

    @Override
    @Transactional
    public void register(User user) {
        // Check if username exists
        if (this.count(new LambdaQueryWrapper<User>()
                .eq(User::getUsername, user.getUsername())) > 0) {
            throw new IllegalArgumentException("用户名已存在");
        }
        
        // Encrypt password
        user.setPassword(passwordUtils.encryptPassword(user.getPassword()));
        
        // Save user
        this.save(user);
    }

    @Override
    public IPage<User> getUsers(Integer pageNum, Integer pageSize, String keyword) {
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        if (StringUtils.hasText(keyword)) {
            wrapper.like(User::getUsername, keyword)
                    .or()
                    .like(User::getRealName, keyword)
                    .or()
                    .like(User::getClassName, keyword);
        }
        return this.page(new Page<>(pageNum, pageSize), wrapper);
    }

    @Override
    @Transactional
    public void updateUser(User user) {
        User existingUser = this.getById(user.getId());
        if (existingUser == null) {
            throw new IllegalArgumentException("用户不存在");
        }
        
        // Check if username is changed and if new username exists
        if (!existingUser.getUsername().equals(user.getUsername())) {
            if (this.count(new LambdaQueryWrapper<User>()
                    .eq(User::getUsername, user.getUsername())) > 0) {
                throw new IllegalArgumentException("用户名已存在");
            }
        }
        
        // Don't update password here
        user.setPassword(null);
        this.updateById(user);
    }

    @Override
    @Transactional
    public void deleteUser(Long id) {
        User user = this.getById(id);
        if (user == null) {
            throw new IllegalArgumentException("用户不存在");
        }
        this.removeById(id);
    }

    @Override
    public User getCurrentUser() {
        Long userId = BaseContext.getCurrentId();
        if (userId == null) {
            throw new IllegalStateException("用户未登录");
        }
        User user = this.getById(userId);
        if (user == null) {
            throw new IllegalStateException("用户不存在");
        }
        // 出于安全考虑，清除密码信息
        user.setPassword(null);
        return user;
    }

    @Override
    @Transactional
    public void changePassword(Long userId, String oldPassword, String newPassword) {
        User user = this.getById(userId);
        if (user == null) {
            throw new IllegalArgumentException("用户不存在");
        }
        
        if (!passwordUtils.checkPassword(oldPassword, user.getPassword())) {
            throw new IllegalArgumentException("原密码错误");
        }
        
        user.setPassword(passwordUtils.encryptPassword(newPassword));
        this.updateById(user);
    }
} 